package com.example.benefitcommunity.util;

import com.example.benefitcommunity.dao.BcUserDao;
import com.example.benefitcommunity.entity.BcUser;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Random;

/**
 * @author makejava
 */
@Component
public class UserNameUtil {
    /**
     * 解决注入为null指针
     */
    @Resource
    private BcUserDao Dao;

    public static BcUserDao userDao;

    /**
     * 注解初始化实例
     */
    @PostConstruct
    public void getUserDao() {
        userDao = this.Dao;
    }

    /**
     * 变量
     */
    public static final String CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    public static final int USERNAME_LENGTH = 6;


    /**
     * 生成随机字符串
     */
    public static String generateRandomString(int length) {
        Random random = new Random();
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(CHARACTERS.length());
            sb.append(CHARACTERS.charAt(index));
        }
        return sb.toString();
    }


    /**
     * 判断用户是否存在
     */
    public static boolean isUsernameExists(String username) {
        BcUser user = userDao.queryByName(username);
        return !(user ==null);
    }


    /**
     * 随机用户名称
     */
    public static String generateUniqueUsername() {
        String username;
        do {
            username = generateRandomString(USERNAME_LENGTH);
        } while (isUsernameExists(username));
        return username;
    }
}
